
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wu_you/res/app_style.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/utils/regular_utils.dart';

enum TextType { phone, email, number, idCard, authCode, decimal, search,password, none }

class TextFormFieldWidget extends StatefulWidget {
  final String hintText;
  final Widget icon;
  final Widget prefixIcon;
  final double prefixSpace;
  final double prefixIconWidth;
  final Widget suffixIcon;
  final double suffixIconWidth;
  final TextEditingController controller;
  final InputBorder enabledBorder;
  final Color fillColor;
  final bool isFill;
  final TextDirection textDirection;
  final double height;
  final bool needUnderline;
  final int maxLines;
  final int maxLength;
  final String errorText; //错误文本
  final TextType type;
  final bool openEditValidation; //限制输入其他字符 目前手机号验证码
  final bool showCount; //显示计数
  final ValueChanged<String> onFieldSubmitted;
  final bool readOnly;
  final bool closeClear;
  final bool validatorStatus;
  final TextInputType keyboardType;
  const TextFormFieldWidget(
      {Key key,
      this.hintText,
      this.icon,
      this.prefixSpace = 3,
      this.prefixIcon,
      this.suffixIcon,
      this.prefixIconWidth = 0,
      this.suffixIconWidth = 0,
      this.controller,
      this.enabledBorder,
      this.fillColor,
      this.isFill = false,
      this.textDirection,
      this.height = 45,
      this.needUnderline = true,
      this.maxLines = 1,
      this.maxLength,
      this.errorText,
      this.type,
      this.openEditValidation = false,
      this.showCount = false,
      this.onFieldSubmitted,this.readOnly = false,this.closeClear = false,this.validatorStatus = true,this.keyboardType
      })
      : super(key: key);

  @override
  _TextFormFieldWidgetState createState() => _TextFormFieldWidgetState();
}

class _TextFormFieldWidgetState extends State<TextFormFieldWidget> {
  List<Widget> _prefixIcon = [];
  double _leftWidth = 0;
  double _rightWidth = 0;
  TextEditingController _controller;
  int _maxLength;
  bool _obscureText = false;
  @override
  void initState() {
    List<Widget> children = [];
    if (widget.icon != null) {
      children.add(widget.icon);
      _leftWidth = widget.prefixIconWidth != 0 ? widget.prefixIconWidth : 80;
    }
    if (widget.prefixIcon != null) {
      children.add(SizedBox(width: widget.prefixSpace));
      children.add(widget.prefixIcon);
      _leftWidth = widget.prefixIconWidth != 0 ? widget.prefixIconWidth : 80;
    }
    if (widget.suffixIcon != null) {
      _rightWidth = widget.suffixIconWidth != 0 ? widget.suffixIconWidth : 80;
    }
    _controller = widget.controller;
    if (_controller == null) {
      _controller =  TextEditingController();
    }
    _prefixIcon = children;
    if( widget.type == TextType.password) {
      _obscureText = true;
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    InputBorder inputBorder;
    if (!widget.needUnderline) {
      inputBorder = UnderlineInputBorder(borderSide: BorderSide.none);
    } else {
      inputBorder = widget.enabledBorder ??
          UnderlineInputBorder(
              borderSide:
                  BorderSide(width: 0.3, color: AppColors.textHintColor));

        if(widget.type == TextType.search) {
          inputBorder = OutlineInputBorder(
              borderSide: BorderSide(color: AppColors.textHintColor),
              borderRadius: BorderRadius.circular(22.5));

      }
    }
    TextInputType keyboardType = TextInputType.text;
    _maxLength = widget.maxLength;
    List<TextInputFormatter> inputFormatters = [];
    TextInputAction inputAction = TextInputAction.none;
    switch (widget.type) {
      case TextType.number:
        keyboardType = TextInputType.number;
        break;
      case TextType.phone:
        keyboardType = TextInputType.number;
        _maxLength = 11;
        inputFormatters = [LengthLimitingTextInputFormatter(_maxLength)];
        break;
      case TextType.authCode:
        keyboardType = TextInputType.number;
        _maxLength = 6;
        inputFormatters = [LengthLimitingTextInputFormatter(_maxLength)];
        break;
      case TextType.decimal:
        keyboardType = TextInputType.numberWithOptions(decimal: true);
        _maxLength = 11;
        inputFormatters = [LengthLimitingTextInputFormatter(_maxLength)];
        break;
      case TextType.search:
        inputAction = TextInputAction.search;
        break;
      default:
        keyboardType = widget.keyboardType ?? TextInputType.text;
        break;
    }
    Widget suffixIcon = widget.suffixIcon;
    bool isPassword = widget.type == TextType.password;
    if(widget.suffixIcon == null){
      if(_controller.text.isEmpty == false && !widget.closeClear) {

        suffixIcon = Container(
            child: Visibility(visible: true, child: IconButton(onPressed: () {
              if(!isPassword) {
                _controller.clear();
              }else{
                _obscureText = !_obscureText;
              }
              setState(() {

              });
            }, icon: Icon(isPassword?Icons.remove_red_eye:Icons.close, size: 15,),color:isPassword && !_obscureText?AppColors.primaryColor: AppColors.textHintColor,)));
      }
    }else{

      Widget child;
      List<Widget> children = [];
      if(_controller.text.isEmpty == false && !widget.closeClear) {
        child = Container(
            child: Visibility(visible: true, child: IconButton(onPressed: () {
              if(!isPassword) {
                _controller.clear();
              }else{
                _obscureText = !_obscureText;
              }
              setState(() {

              });
            }, icon: Icon(isPassword?Icons.remove_red_eye:Icons.close, size: 15,),color:isPassword && !_obscureText?AppColors.primaryColor: AppColors.textHintColor,)));
        children.add(child);
      }
      children.add(widget.suffixIcon);
      suffixIcon = Container(width: _rightWidth + 50,height: double.infinity, child: Row(mainAxisAlignment: MainAxisAlignment.end,children: children,),color: Colors.transparent);
    }
    Widget child = Padding(
        padding: EdgeInsets.symmetric(horizontal: 10),
        child: TextFormField(
          obscureText: _obscureText,
          maxLines: widget.maxLines,
          readOnly: widget.readOnly,
          maxLength: widget.showCount ? widget.maxLength : null,
          inputFormatters: inputFormatters,
          controller: _controller,
          keyboardType: keyboardType,
          textInputAction: inputAction,
          textDirection: widget.textDirection ?? TextDirection.ltr,
          textAlignVertical: suffixIcon != null
              ? TextAlignVertical.center
              : TextAlignVertical.top,
          validator: (value) {
            if(!widget.validatorStatus){
              return null;
            }
            dynamic validatorText(bool type) {
              return type ? null : widget.errorText ?? "请输入正确格式";
            }

            switch (widget.type) {
              case TextType.number:
                return validatorText(RegularUtils.onlyNumber(value));
                break;
              case TextType.email:
                return validatorText(RegularUtils.isEmail(value));
                break;
              case TextType.idCard:
                return validatorText(RegularUtils.idCard(value));
                break;
              case TextType.phone:
                return validatorText(RegularUtils.phone(value));
                break;
            }
            return value.isNotEmpty
                ? null
                : widget.errorText ?? widget.hintText;
          },
          onChanged: (value) {
            if (widget.openEditValidation) {
              List<String> str = value.split(RegExp(r"\D+"));
              String newStr = str.join();
              // print(newStr);
              _controller.text = newStr;
              _controller.selection = TextSelection.fromPosition(
                  TextPosition(offset: _controller.text.length));
            }
            if(widget.maxLength != null){
              if(value.length > widget.maxLength) {
                String newStr = value.substring(0, widget.maxLength);
                _controller.text = newStr;
                _controller.selection = TextSelection.fromPosition(
                    TextPosition(offset: _controller.text.length));
              }
            }
            if(!widget.closeClear) {
              setState(() {
              });
            }
            if(widget.onFieldSubmitted != null) {
              widget.onFieldSubmitted(value);
            }
          },
          onSaved: (value) {
            // print(value);
          },
          onFieldSubmitted: (value) {
            if(widget.onFieldSubmitted != null){
              widget.onFieldSubmitted(value);
            }
          },
          style: TextStyle(fontSize: 14),
          decoration: InputDecoration(
            hintText: widget.hintText ?? "请输入手机号",
            hintStyle: TextStyle(fontSize: 14),
            hintTextDirection: widget.textDirection,
            prefixIcon: Row(
                mainAxisAlignment: _prefixIcon.length == 0
                    ? MainAxisAlignment.center
                    : MainAxisAlignment.start,
                children: _prefixIcon),
            suffixIcon: suffixIcon,
            suffixIconConstraints: BoxConstraints.loose(Size(_rightWidth + (!widget.closeClear ? 50: 0), 50)),
            prefixIconConstraints: BoxConstraints.loose(Size(_leftWidth, 45)),
            contentPadding: EdgeInsets.zero,
            enabledBorder: inputBorder,
            focusedBorder: inputBorder,
            errorBorder: UnderlineInputBorder(borderSide: BorderSide.none),
            focusedErrorBorder:
                UnderlineInputBorder(borderSide: BorderSide.none),
            border: UnderlineInputBorder(borderSide: BorderSide.none),
            disabledBorder: UnderlineInputBorder(borderSide: BorderSide.none),
            helperText: null,
            // isDense: true
            // filled: true
            fillColor: widget.fillColor,
            filled: widget.isFill,
            counter: null,
            counterStyle: AppStyle.textStyle
                .copyWith(color: AppColors.textSecondaryColor),
          ),
        ));
    // if (widget.height != null) {
    //  return child = SizedBox(
    //     height: widget.height,
    //     child: child,
    //   );
    // }

    // if(widget.wordLimit){
    //   return Stack(children: [
    //     child,
    //     Align(alignment: Alignment(0.8,0.8),child: Text("0/200"),)
    //   ],);
    // }
    return child;
  }
}
